/**
 * Created by zhangb on 2015/9/22.
 */

var data = new FormData();
data.append("name","value");
function createXHR()
{
    if(typeof XMLHttpRequest != "undefined")
    {
        return new XMLHttpRequest();
    }else if( typeof ActiveXObject != "undefined") {
        if(typeof arguments.callee.activeXString != "string")
        {
            var versions = ["MSXML2.XMLHttp.6.0","MSXML2.XMLHttp.3.0","MSXML2.XMLHttp"],
                i,len;
            for(i=0,len=versions.length;i<len;i++)
            {
                try{
                    new ActiveXObject(versions[i]);
                    arguments.callee.activeXString = versions[i];
                    break;
                } catch (ex){

                }
            }
        }
        return new ActiveXObject(arguments.callee.activeXString);

    }else{
        throw new Error("NO XHR object available.")
    }
}

var xhr = createXHR();
//load 事件（onload 接受一个event 对象） 替代  onreadystatechange事件
xhr.onreadystatechange = function()
{
    if(xhr.readyState == 4)
    {
        try
        {
            if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304)
            {
                alert(xhr.responseText);
            }else{
                alert("Request was unsuccessfull:" + xhr.statis);
            }
        }catch (ex){
            //假设由ontimeout 时间处理程序处理
            alert('ontimeout event');
        }

    }
};
xhr.open("post","index.php",true);

var form = document.getElementById("userinfo");
//超时限定 timeout 属性
xhr.timeout = 1000;
xhr.ontimeout = function()
{
    alert("Request did not return in a seconde");
};
//  overrideMimeType() 重写xhr响应的MIME类型
xhr.overrideMimeType("text/xml");

// progress 事件 在浏览器接受新数据期间周期性地触发
xhr.progress = function()
{
    var divStatus = document.getElementById("status");
    if(event.lengthComputable)
    {
        divStatus.innerHTML = "Received" + event.position + "of" + event.totalSize + "bytes";
    }
};
xhr.send(new FormData(form));


function createCORSRequest(method,url)
{
    var xhr = new XMLHttpRequest();
    if("withCredentials" in xhr)
    {
        xhr.open(method,url,ture);
    }else if(typeof XDomainRequest != "undefined"){
        vxhr = new XDomainRequest();
        xhr.open(method,url);
    }else{
        xhr = null;
    }
    return xhr;
}
var request = createCORSRequest("get","http://www.somewhere-else.com/page/");
if(request)
{
    request.onload = function()
    {
        //处理 request.responseText
    }
    request.send();
}